#include "qpc.h"
#include "ui_qpc.h"

QPC::QPC(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::QPC)
{
    ui->setupUi(this);
    myserial=new MySerialPort();
    RefreshTimer =new QTimer(this);
    RefreshTimer->start(10);
    SendTimer =new QTimer(this);
    visionthread =new VisionThread();
    SupperSendDialg=new QDialog();

    SD_D_ID_ComboBox=new QComboBox(SupperSendDialg);
    SD_R_ID_ComboBox=new QComboBox(SupperSendDialg);
    SD_Send_Button=new QPushButton(SupperSendDialg);
    SDLayout=new QGridLayout(SupperSendDialg);

    connect(RefreshTimer,&QTimer::timeout,this,&QPC::RefreshTimerUpdate);
    connect(SendTimer,&QTimer::timeout,this,&QPC::SendTimerUpdate);
    connect(myserial,&MySerialPort::SerialPassDatas,this,&QPC::ReveiveSerialPortData);
    connect(visionthread, &VisionThread::ConveyData, this, &QPC::ReveiveVisionData);
    connect(this, &QPC::CameraStatus,visionthread,&VisionThread::Camera_Init);
    isOSC=false;
    isHex=false;
    isTimeLine=false;
    isAutoNewLine= false;
    isDelayedTx=false;
    isSupperCom=false;
    isOpenCamera = false;
    VisionThread_Flag = false;
    nLine=0;
    LineNum=0;

    Vision_Line_CD.append("正向");
    Vision_Line_CD.append("逆90°");
    ui->VisionCD_PortName_comboBox_2->clear();
    ui->VisionCD_PortName_comboBox_2->insertItems(0, Vision_Line_CD);

    ui->PortName_comboBox->clear();
}

QPC::~QPC()
{
    if (isOpenCamera)
        visionthread->Camera_Init(0,ChooseCamera);
    ui->label_10->clear();
    visionthread->isStop=true;
    StopVisionThread();
    delete ui;
}

void QPC::on_SeekSerialPort_pushButton_clicked()
{
    ui->PortName_comboBox->clear();
    SerialNum.clear();
    SerialPortNameNum.clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
       SerialPortNameNum.append(info.portName());
       SerialNum.append(info.description()+"("+info.portName()+")");
    }
    ui->PortName_comboBox->insertItems(0, SerialNum);
}

void QPC::on_OpenSerialPort_pushButton_clicked()
{
    int num;
    num=ui->PortName_comboBox->currentIndex();
//    ui->ShowDatas_plainTextEdit->insertPlainText(tr("%1").arg(num)+"\n");

    if(num!=-1)
    myserial->serial.setPortName(SerialPortNameNum[num]);
    myserial->SetSerialPortParameter(ui->BaudRate_comboBox->currentIndex());
    if(ui->OpenSerialPort_pushButton->text()=="打开摄像头串口"){
        if(! myserial->OpenSerialPort()){
            ShowWaringInformation("串口打开失败！");
            myserial->CloseSerialPort();
        }
        else{
            ui->OpenSerialPort_pushButton->setText("关闭摄像头串口");
        }
    }
    else{
        myserial->CloseSerialPort();
        ui->OpenSerialPort_pushButton->setText("打开摄像头串口");
    }
}

void QPC::on_SendOrder_pushButton_clicked()
{
    if(ui->OpenSerialPort_pushButton->text()=="关闭串口"){
        if(!ui->Order_lineEdit->text().isEmpty()){
            if(isSupperCom){

            }
            else{
                myserial->SendDatas(ui->Order_lineEdit->text().toLatin1());//以16进制数的形式发送
            }
        }
        else{
            ShowWaringInformation("没有任何指令输入！");
        }
    }
    else{
        ShowWaringInformation("串口未打开！");
    }
}

void QPC::on_IsHex_checkBox_clicked()
{
    if(ui->IsHex_checkBox->isChecked())
        isHex=true;
    else
        isHex=false;
}

void QPC::on_TimeLine_checkBox_clicked()
{
    if(ui->TimeLine_checkBox->isChecked())
        isTimeLine=true;
    else
        isTimeLine=false;
}

void QPC::on_IsAutoNewLine_checkBox_clicked()
{
    if(ui->IsAutoNewLine_checkBox->isChecked())
        isAutoNewLine=true;
    else
        isAutoNewLine=false;
}

void QPC::on_IsDelayedTx_checkBox_clicked()
{
   if(ui->IsDelayedTx_checkBox->isChecked())
       isDelayedTx=true;
   else
       isDelayedTx=false;
}

void QPC::on_SaveData_pushButton_clicked()
{
    if(ui->ShowDatas_plainTextEdit->toPlainText().isEmpty())
        ShowWaringInformation(tr("没有数据可以保存"));
    else{
        QString FileName = QFileDialog::getSaveFileName(this, tr("保存为"), ".", tr("Text files(*.txt);; files(*.docx *.doc)"));
        QFile file(FileName);
        if (!file.open(QFile::WriteOnly | QFile::Text))
        {

        }
        QTextStream out(&file);
        out << ui->ShowDatas_plainTextEdit->toPlainText();
    }
}

void QPC::on_Clear_pushButton_clicked()
{
    ui->ShowDatas_plainTextEdit->clear();
}

void QPC::on_SupperCom_pushButton_clicked()
{
    if(ui->SupperCom_pushButton->text()=="启动高级传输"){
        isSupperCom=true;
        ui->SupperCom_pushButton->setText("关闭高级传输");
    }
    else{
        ui->SupperCom_pushButton->setText("打开高级传输");
        isSupperCom=false;
    }
//    ui->SupperCom_pushButton->setDisabled(true);
//    if(ui->SupperCom_pushButton->text()=="启动高级传输"){
//        SetSupperSendDialog();
//        ui->SupperCom_pushButton->setText("关闭高级传输");
//        if(ui->Check_comboBox->currentIndex()==0)
//            ui->Check_comboBox->setCurrentIndex(1);
//        isSupperCom=true;
//    }
//    else{
//        ui->SupperCom_pushButton->setText("启动高级传输");
//        ui->Check_comboBox->setCurrentIndex(0);
//        isSupperCom=false;
//    }
}

//显示警告提示信息
void  QPC::ShowWaringInformation(QString info)
{
    QMessageBox::warning(this,"警告",info,QMessageBox::Ok,QMessageBox::Cancel);
}

void QPC::RefreshTimerUpdate()
{
    update();
}

void QPC::SendTimerUpdate()
{

}

//测试专用
//void QPC::ReveiveSerialPortData(QByteArray data)
//{
//    ui->ShowDatas_plainTextEdit->verticalScrollBar()->setValue(ui->ShowDatas_plainTextEdit->verticalScrollBar()->maximum());//设置光标
//    ui->ShowDatas_plainTextEdit->insertPlainText(tr("%1").arg(mymath.FourBytesToFloat(data))+"\n");
//}
void  QPC::ReveiveSerialPortData(QByteArray data)
{
    ui->ShowDatas_plainTextEdit->setTextCursor(ui->ShowDatas_plainTextEdit->textCursor());//设置光标
    if(isSupperCom){
        if(data.contains("Error"))
            ui->ShowDatas_plainTextEdit->insertPlainText("接收的数据：Error\n");
        else
            ui->ShowDatas_plainTextEdit->insertPlainText("接收的数据："+tr("%1").arg(mymath.FourBytesToFloat(data))+"\n");
    }
    else{
        if(!data.contains("Q"))
        {
            ui->ShowDatas_plainTextEdit->insertPlainText(data);
        }
        else{
            QString WChar;
            QByteArray NChar;
            int i;
            ui->IsHex_checkBox->setDisabled(false);
            int datalength=data.length();
            for( i=0;i<datalength;i++){
                if(data.at(i)!='Q'){
                    WChar[i]=data[i];
                }
                else{
                       nLine=data.at(i+1)-48;
                       if(nLine>LineNum)
                           LineNum=nLine;
                       switch (nLine) {
                       case 1:
                           Line1Name=WChar;
                           break;
                       case 2:
                           Line2Name=WChar;
                           break;
                       case 3:
                           Line3Name=WChar;
                           break;
                       case 4:
                           Line4Name=WChar;
                           break;
                       case 5:
                           Line5Name=WChar;
                           break;
                       default:
                           break;
                       }
                       break;
                }
            }
            for(int j=i+2;j<datalength;j++){
                if(data[j]!='Q')
                    NChar[j-i-2]=data[j];
                else
                    i++;
            }
            ui->ShowDatas_plainTextEdit->insertPlainText(WChar+NChar);
        }
    }
}

void QPC::on_SearchCamera_pushButtonn_clicked()
{
    ui->Camera_comboBox->clear();
//    ui->PortName_comboBox->insertItem(0, myserial->SeekSerialPort());
//    ui->PortName_comboBox->setCurrentIndex(0);

    CameraNum.clear();
    //ui->Camera_comboBox->clear();
    foreach (const QCameraInfo &cameraInfo, QCameraInfo::availableCameras())
    {
        CameraNum.append(cameraInfo.description());
    }
     ui->Camera_comboBox->insertItems(0, CameraNum);

//    ui->ShowDatas_plainTextEdit->insertPlainText("Device name: " + cameraInfo.description()+"\n");
}

void QPC::on_OpenCamera_pushButton_clicked()
{
    ChooseCamera=ui->Camera_comboBox->currentIndex();
    if(ChooseCamera!=-1)
    {
        if (ui->OpenCamera_pushButton->text() == "打开摄像头"){
            ui->OpenCamera_pushButton->setText(tr("关闭摄像头"));
            isOpenCamera = true;
            emit CameraStatus(isOpenCamera,ChooseCamera);//发射信号
            visionthread->isStop=false;
            if(!VisionThread_Flag)
            {
                StartVisionThread();
                VisionThread_Flag = true;
            }
        }
        else {
            ui->OpenCamera_pushButton->setText(tr("打开摄像头"));
            isOpenCamera = false;
            emit CameraStatus(isOpenCamera,ChooseCamera);//发射信号
//            StopVisionThread();
        }
    }
    else
    {
        ShowWaringInformation("Open Camera Sensor Failed！");
    }

}

void QPC::StartVisionThread()
{
    visionthread->start();
}

void QPC::StopVisionThread()
{
    visionthread->wait();
    visionthread->terminate();
}

//   图像转换
QImage QPC::Mat2QImage(Mat cvImg)
{

    QImage qImg;
    if(cvImg.channels()==3)                             //3 channels color image
    {
        cv::cvtColor(cvImg,cvImg,CV_BGR2RGB);
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols, cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_RGB888);
//        const uchar *pSrc = (const uchar*)cvImg.data;
//        // Create QImage with same dimensions as input Mat
//        QImage image(pSrc, cvImg.cols, cvImg.rows, cvImg.step, QImage::Format_RGB888);
//        return image.rgbSwapped();
    }
    else if(cvImg.channels()==1)                    //grayscale image
    {
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols,cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_Indexed8);
    }
    else
    {
        qImg =QImage((const unsigned char*)(cvImg.data),
                    cvImg.cols,cvImg.rows,
                    cvImg.cols*cvImg.channels(),
                    QImage::Format_RGB888);
    }
    return qImg;


}

void QPC::ReveiveVisionData(float dx, float dy, float angle)
{
    float F_dx,F_dy,F_angle;
    //本地显示
    //刷新坐标系选项
    visionthread->getline->Line_coordinate_convert=ui->VisionCD_PortName_comboBox_2->currentIndex()+1;

    //ui->ShowDatas_plainTextEdit->verticalScrollBar()->setValue(ui->ShowDatas_plainTextEdit->verticalScrollBar()->maximum());
    ui->Vision_plainTextEdit->verticalScrollBar()->setValue(ui->Vision_plainTextEdit->verticalScrollBar()->maximum());
    ui->VisionLineDSP_plainTextEdit->verticalScrollBar()->setValue(ui->VisionLineDSP_plainTextEdit->verticalScrollBar()->maximum());

    ui->Vision_plainTextEdit->insertPlainText("发送dx："+tr("%1").arg(dx)+"        ");
    ui->Vision_plainTextEdit->insertPlainText("dy:"+tr("%1").arg(dy)+"\n");
    ui->VisionDSP_lineEdit->setText(tr("%1").arg(visionthread->getline->Line_DSP));
    ui->VisionLineDSP_plainTextEdit->insertPlainText("DSP:"+tr("%1").arg(visionthread->getline->Line_DSP)+"\n");

    //补偿段
    ui->Original_dx_lineEdit->setText(tr("%1").arg(dx));
    ui->Original_dy_lineEdit->setText(tr("%1").arg(dy));
    ui->Original_angle_lineEdit->setText(tr("%1").arg(angle));
//    ui->Final_dx_lineEdit->setText(tr("%1").arg(dx*ui->K_dx_doubleSpinBox->text().toFloat()+ui->B_dx_doubleSpinBox->text().toFloat()));
//    ui->Final_dy_lineEdit->setText(tr("%1").arg(dy*ui->K_dy_doubleSpinBox->text().toFloat()+ui->B_dy_doubleSpinBox->text().toFloat()));
//    ui->Final_angle_lineEdit->setText(tr("%1").arg(angle*ui->K_angle_doubleSpinBox->text().toFloat()+ui->B_angle_doubleSpinBox->text().toFloat()));
//    F_dx=ui->Final_dx_lineEdit->text().toFloat();
//    F_dy=ui->Final_dy_lineEdit->text().toFloat();
//    F_angle=ui->Final_angle_lineEdit->text().toFloat();

    F_dx=dx;
    F_dy=dy;
    F_angle=angle;

    //显示图片
    Mat lineV,lineBeThreshold,lineLine,lineSrc;
    visionthread->getline->TextShow(LINE_SHOW_V,lineV);
    visionthread->getline->TextShow(LINE_SHOW_BETHRESHOLD,lineBeThreshold);
   // visionthread->getline->TextShow(LINE_SHOW_LINE,lineLine);
    visionthread->getline->TextShow(LINE_SHOW_SRC,lineSrc);
    //QLine_Line=Mat2QImage(lineLine);
    QLine_Bethreshold=Mat2QImage(lineBeThreshold);
    QlinV=Mat2QImage(lineV);
    QLine_Src=Mat2QImage(lineSrc);
    ui->label_4->setPixmap(QPixmap::fromImage(QlinV));
    ui->label_9->setPixmap(QPixmap::fromImage(QLine_Bethreshold));
    //ui->VisionLineShow_label_17->setPixmap(QPixmap::fromImage(QLine_Line));
    ui->label_11->setPixmap(QPixmap::fromImage(QLine_Src));
    //发送
    if(j==1)
        SendVisionData_dx(F_dx);
    else if(j==2)
        SendVisionData_dy(F_dy);
    else if(j==3)
        SendVisionData_angle(F_angle);
    else
        j=0;
    j++;

}

void QPC::SetSupperSendDialog()
{
//    SD_R_Items<<tr("底盘")<<tr("电源管理")<<tr("手柄")<<tr("其它单片机");
//    SD_D1_Items<<tr("普通数据")<<tr("待扩展");
//    SD_D2_Items<<tr("普通数据")<<tr("待扩展");
//    SD_D3_Items<<tr("普通数据")<<tr("待扩展");
//    SD_D4_Items<<tr("普通数据")<<tr("待扩展");
//    SupperSendDialg->resize(200,50);
//    SupperSendDialg->setWindowTitle(tr("高级传输"));
////    SupperSendDialg->setWindowState(Qt::WindowStaysOnTopHint);
//    SD_R_ID_ComboBox->insertItems(0,SD_R_Items);
//    SD_D_ID_ComboBox->insertItems(0,SD_D1_Items);

//    switch(SD_R_ID_ComboBox->currentIndex()){

//        case 0:SD_D_ID_ComboBox->insertItems(0,SD_D1_Items);
//               SD_D_ID_ComboBox->clear();
//        break;
//        case 1:SD_D_ID_ComboBox->insertItems(0,SD_D2_Items);
//               SD_D_ID_ComboBox->clear();
//        break;
//        case 2:SD_D_ID_ComboBox->insertItems(0,SD_D3_Items);
//               SD_D_ID_ComboBox->clear();
//        break;
//        case 3:SD_D_ID_ComboBox->insertItems(0,SD_D4_Items);
//               SD_D_ID_ComboBox->clear();
//        break;
//    }

//    SD_Send_Button->setText(tr("发送"));
//    SDLayout->addWidget(SD_R_ID_ComboBox,0,0);
//    SDLayout->addWidget(SD_D_ID_ComboBox,0,1);
//    SDLayout->addWidget(SD_Data_LineEdit,0,2);
//    SDLayout->addWidget(SD_Send_Button,0,3);
//    SupperSendDialg->show();
}

//void QPC::on_SD_Send_Button_clicked()
//{
//    ShowWaringInformation(tr("OK"));
////    char str[4];
////    mymath.FloatTo4Bytes(SD_Send_Button->text().toFloat(),str);
////    myserial->SendDatas(str);

//}

void QPC::SendVisionData_dx(float data)
{
    myserial->SendDatas(ComPro.VisionDatasPakeage(ComPro.ID_Vision_dx,data));
}

void QPC::SendVisionData_dy(float data)
{
    myserial->SendDatas(ComPro.VisionDatasPakeage(ComPro.ID_Vision_dy,data));
}

void QPC::SendVisionData_angle(float data)
{
    myserial->SendDatas(ComPro.VisionDatasPakeage(ComPro.ID_Vision_angle,data));
}

void QPC::closeEvent(QCloseEvent *event)
{
//    visionthread->isStop=true;
//    isOpenCamera = false;
//    StopVisionThread();
//    QWidget::closeEvent(event);
}

void QPC::Delay_ms(int msec)
{
    QDateTime last=QDateTime::currentDateTime().addMSecs(msec);
    QDateTime now;
    while(1){
        if(QDateTime::currentDateTime()<last)
            break;
    }
}


void QPC::on_isSendHex_checkBox_clicked()
{

}



void QPC::on_VisionClear_pushButton_clicked()
{
     ui->Vision_plainTextEdit->clear();
     ui->VisionLineDSP_plainTextEdit->clear();
}


void QPC::on_VisionClearData_pushButton_clicked()
{
    ui->Original_dx_lineEdit->setText(tr("%1").arg(0.0));
    ui->Original_dy_lineEdit->setText(tr("%1").arg(0.0));
    ui->Original_angle_lineEdit->setText(tr("%1").arg(0.0));
    visionthread->data[1]=0.0;
    visionthread->data[2]=0.0;
}

void QPC::on_pushButton_clicked()
{
    ui->label_4->clear();
    ui->label_9->clear();
    ui->label_11->clear();

    ui->label_4->setText("gray");
    ui->label_9->setText("channel_s");
    ui->label_11->setText("src");
}

void QPC::on_pushButton_2_clicked()
{
    int num;
    num=ui->PortName_comboBox->currentIndex();
//    ui->ShowDatas_plainTextEdit->insertPlainText(tr("%1").arg(num)+"\n");

    if(num!=-1)
    myserial->serial_1.setPortName(SerialPortNameNum[num]);
    myserial->SetSerialPortParameter_1(ui->BaudRate_comboBox->currentIndex());
    if(ui->pushButton_2->text()=="打开串口"){
        if(! myserial->OpenSerialPort_1()){
            ShowWaringInformation("串口打开失败！");
            myserial->CloseSerialPort_1();
        }
        else{
            ui->pushButton_2->setText("关闭串口");
        }
    }
    else{
        myserial->CloseSerialPort_1();
        ui->pushButton_2->setText("打开串口");
    }
}
